<?php

namespace app\admin\controller;

use DateTime;
use think\Cache;
use think\Controller;
use think\Db;
use think\Loader;
use think\Request;
use think\Queue;

class Manage extends Common
{
    /**
     * 列表示例
     * */
    public function listDemo()
    {
        $list = Db::name('menu')->paginate(2);
        $this->assign('list', $list);

        $this->assign('title', '列表示例');
        return $this->fetch();
    }

    /**
     * 列表导出示例
     * */
    public function exportListDemo()
    {
        $title = '文件名';
        $th = ['标题一', '标题二', '标题三'];
        $td = ['key1', 'key2', 'key3'];
        $data = [
            [
                'key1' => 'value1',
                'key2' => 'value2',
                'key3' => 'value3',
            ], [
                'key1' => 'value1',
                'key2' => 'value2',
                'key3' => 'value3',
            ]
        ];

        exportExcel($title, $th, $td, $data);
    }

    /**
     * 表单示例
     * */
    public function formDemo()
    {
        if (Request()->isPost()) {
            $input = Request()->param();

            echo "<pre>";
            print_r($input);
            exit;
        }
        $this->assign('title', '表单示例');
        return $this->fetch();
    }

    /**
     * 视频分片上传示例
     * */
    public function uploadVideo()
    {
        $this->assign('title', '视频分片上传示例');
        return $this->fetch();
    }

    /**
     * 统计图示例
     * */
    public function chartDemo()
    {
        $this->assign('title', '统计图');
        return $this->fetch();
    }

    /**
     * 树形列表示例
     * */
    public function treeDemo()
    {
        return $this->fetch();
    }

    /**
     * 树状图原始demo
     * */
    public function tree()
    {
        $this->assign('title', 'test');
        return $this->fetch();
    }

    /**
     * iconfont
     * */
    public function iconfont()
    {
        $this->assign('title', 'iconfont');
        return $this->fetch();
    }


    /**
     * 用户列表
     * */
    public function userList()
    {
        $input = Request()->param();

        $mobile = $input['mobile'] ? : '';
        $up_user_id = $input['up_user_id'] ? : 0;

        $where['user_type'] = 3;
        if ($mobile) $where['mobile'] = ['LIKE', "%{$mobile}%"];
        if ($up_user_id) $where['up_user_id'] = $up_user_id;

        $list = Db::name('user')->where($where)->order('id desc')->paginate();

        $spread_user_list = Db::name('user')->where(['user_type' => 1, 'status' => 1])->select();
        $this->assign('spread_user_list', $spread_user_list);

        $this->assign('list', $list);
        return $this->view->fetch();
    }

    /**
     * 启用/禁用
     * */
    public function doUserStatus()
    {
        $id = Request()->param('id');
        $status = Request()->param('status');

        if (empty($id)) adminReturn(2, 'ID缺失');

        $info = Db::name('user')->where(['id' => $id])->find();
        if ($info) {
            $res = Db::name('user')->where(['id' => $id])->setField('status', $status);
            if ($res) {
                adminReturn(1, '操作成功', url('userList'));
            } else {
                adminReturn(2, '操作失败');
            }
        } else {
            adminReturn(2, '数据不存在或已删除');
        }
    }

    /**
     * 结算规则列表
     * */
    public function settlementRuleList()
    {
        $search_value = Request()->param('search_value', '');

        $where = [];
        if ($search_value) $where['teacher|course'] = ['LIKE', "%{$search_value}%"];

        $list = Db::name('settlement_rule')->where($where)->order('id desc')->paginate()->each(function ($val) {
            $val['config'] = json_decode($val['config'], true);
            return $val;
        });
        $this->assign('list', $list);

        $this->assign('title', '结算规则列表');
        return $this->fetch();
    }

    /**
     * 新增/编辑 结算规则
     * */
    public function doSettlementRule()
    {
        if (Request()->isPost()) {
            $input = Request()->param();

            $id = $input['id'];
            $name = $input['name'];               // 名称
            $teacher_id = $input['teacher_id'];   // 老师id
            $teacher = $input['teacher'];         // 老师
            $course_id = $input['course_id'];     // 课程id
            $course = $input['course'];           // 课程
            $config_arr = $input['rules'] ? : ''; // 分期拨付比例：[{'day': 10, 'rate': 30}, {'day': 20, 'rate': 30}, {'day': 30, 'rate': 40}]

            if (empty($name)) adminReturn(2, '请输入规则名称');
            if (empty($teacher_id) || empty($teacher) || empty($course_id) || empty($course)) apiReturn(2, '请选择老师和课程');

            $where = ['teacher_id' => $teacher_id, 'course_id' => $course_id];
            if ($id) $where['id'] = ['neq', $id];
            $count = Db::name('settlement_rule')->where($where)->count();
            if ($count) adminReturn(2, '该老师和课程的结算规则已存在');

            if (empty($config_arr)) adminReturn(2, '请输入拨付比例');

            // 验证分期拨付比例的有效性
            $total_rate = 0;
            $previous_day = 0;
            $day_set = [];

            foreach ($config_arr as $index => $rule) {
                // 检查必要字段是否存在
                if (!isset($rule['day']) || !isset($rule['rate'])) {
                    adminReturn(2, "第" . ($index + 1) . "条分期规则缺少必要字段");
                }

                $day = $rule['day'];
                $rate = $rule['rate'];

                // 验证天数为正整数
                if (!is_numeric($day) || intval($day) <= 0 || intval($day) != $day) {
                    adminReturn(2, "第" . ($index + 1) . "条分期规则的天数必须为正整数");
                }

                // 验证天数不重复
                if (in_array($day, $day_set)) {
                    adminReturn(2, "第" . ($index + 1) . "条分期规则的天数与其他规则重复");
                }
                $day_set[] = $day;

                // 验证比例为非负数且不超过100
                if (!is_numeric($rate) || $rate < 0 || $rate > 100) {
                    adminReturn(2, "第" . ($index + 1) . "条分期规则的比例必须为0-100之间的数值");
                }

                $total_rate += $rate;
            }

            // 验证比例总和为100%
            if (abs($total_rate - 100) > 0.0001) { // 允许微小误差
                adminReturn(2, "分期拨付比例总和必须为100%");
            }

            // 按天数升序排序
            $sort = array_column($config_arr, 'day');
            array_multisort($sort, SORT_ASC, $config_arr);

            // 验证排序后天数是否递增
            foreach ($config_arr as $index => $rule) {
                $day = $rule['day'];
                if ($index > 0 && $day <= $previous_day) {
                    adminReturn(2, "分期规则天数必须严格递增");
                }
                $previous_day = $day;
            }

            // 准备保存到数据库的数据
            $config_json = json_encode($config_arr, JSON_UNESCAPED_UNICODE);

            $data = [
                'name' => $name,
                'teacher_id' => $teacher_id,
                'teacher' => $teacher,
                'course_id' => $course_id,
                'course' => $course,
                'config' => $config_json
            ];

            Db::startTrans();
            try {
                if ($id) {
                    // 更新
                    $data['update_time'] = time();
                    $res = Db::name('settlement_rule')->where(['id' => $id])->update($data);
                } else {
                    // 新增
                    $data['create_time'] = time();
                    $res = Db::name('settlement_rule')->insert($data);
                }
                if (!$res) {
                    Db::rollback();
                    adminReturn(2, '保存失败');
                }

                $res = createOperationLog('doSettlementRule');
                if (!$res) {
                    Db::rollback();
                    adminReturn(2, '保存失败');
                }

                Db::commit();
                adminReturn(1, '保存成功', url('settlementRuleList'));
            } catch (\Exception $e) {
                Db::rollback();
                adminReturn(2, '保存失败');
            }
        } else {
            $id = Request()->param('id');

            $info = [];
            if ($id) {
                $info = Db::name('settlement_rule')->where(['id' => $id])->find();
                $this->assign('info', $info);

                $teacherCourse = ['teacher_id' => $info['teacher_id'], 'course_id' => $info['course_id']];
            } else {
                $teacherCourse = [];
            }
            $this->assign('teacherCourse', json_encode($teacherCourse, JSON_UNESCAPED_UNICODE));
            $this->assign('config', $info['config'] ? : json_encode([]));

            $this->assign('title', '结算规则');
            return $this->view->fetch();
        }
    }

    /**
     * 启用/禁用 结算规则
     * */
    public function settlementRuleStatus()
    {
        $id = Request()->param('id');
        $status = Request()->param('status');

        if (empty($id)) adminReturn(2, 'ID缺失');

        $info = Db::name('settlement_rule')->where(['id' => $id])->find();
        if ($info) {
            Db::startTrans();
            try {
                $res = Db::name('settlement_rule')->where(['id' => $id])->setField('status', $status);
                if (!$res) {
                    Db::rollback();
                    adminReturn(2, '操作失败');
                }

                $res = createOperationLog('settlementRuleStatus');
                if (!$res) {
                    Db::rollback();
                    adminReturn(2, '操作失败');
                }

                Db::commit();
                adminReturn(1, '操作成功');
            } catch (\Exception $e) {
                Db::rollback();
                adminReturn(2, '操作失败' . $e->getMessage());
            }


        } else {
            adminReturn(2, '数据不存在或已删除');
        }
    }

    /**
     * 资金划拨
     * */
    public function allocate()
    {
        $list = Db::name('allocate')->order('id desc')->limit(3)->select();
        $this->assign('list', $list);

        $this->assign('title', '资金划拨');
        return $this->view->fetch();
    }

    /**
     * 划拨记录
     * */
    public function allocateList()
    {
        $input = Request()->param();

        $list = Db::name('allocate')->order('id desc')->paginate();

        $this->assign('list', $list);

        $this->assign('title', '划拨记录');
        return $this->view->fetch();
    }

    /**
     * 手动结算
     * */
    public function userSettlement()
    {
        $this->assign('title', '手动结算');
        return $this->view->fetch();
    }

    /**
     * 结算记录
     * */
    public function settlementList()
    {
        $input = Request()->param();

        $list = Db::name('settlement')->order('id desc')->paginate();

        $this->assign('list', $list);

        $this->assign('title', '结算记录');
        return $this->view->fetch();
    }

    /**
     * 资金拨付设置
     * */
    public function settlementConfig()
    {
        if (Request()->isPost()) {
            $input = Request()->param();

            $month = $input['month'];         // 拨付周期
            $config = $input['config'] ? : '';// 拨付比例：1,2,3

            if (empty($month)) adminReturn(2, '请输入拨付周期');
            if (empty($config)) apiReturn(2, '请输入拨付比例');

            if ($month != (int)$month) adminReturn(2, '拨付周期应为整数');

            $config_arr = explode(',', $config);
            if (count($config_arr) != $month) adminReturn(2, '拨付比例格式错误');
            $is_error = false;
            $sum = 0;
            foreach ($config_arr as $v) {
                $v = (int)$v;
                if ($v <= 0 || $v > 100) {
                    $is_error = true;
                    break;
                } else {
                    $sum += $v;
                }
            }
            if ($is_error) adminReturn(2, '拨付比例应大于0且小于100');
            if ($sum != 100) adminReturn(2, '拨付比例综合应为100');

            Db::startTrans();
            try {
                Db::name('config')->where(['name' => 'SETTLEMENT_MONTH'])->setField('value', $month);
                Db::name('config')->where(['name' => 'SETTLEMENT_CONFIG'])->setField('value', $config);

                Db::commit();

                Cache::clear();

                adminReturn(1, '保存成功');
            } catch (\Exception $e) {
                Db::rollback();
                adminReturn(2, '保存失败');
            }
        } else {
            $config_arr = C('SETTLEMENT_CONFIG');
            $this->assign('config_arr', $config_arr);

            $this->assign('title', '支付配置');
            return $this->view->fetch();
        }
    }

    /**
     * 普通退款列表
     * */
    public function refundList()
    {
        $input = Request()->param();

        $list = Db::name('refund')->order('id desc')->paginate();
        $this->assign('list', $list);

        $this->assign('title', '普通退款列表');
        return $this->view->fetch();
    }

    /**
     * 普通退款详情
     * */
    public function refundDetail()
    {
        $this->assign('title', '详情');
        return $this->view->fetch();
    }

    /**
     * 操作日志
     * */
    public function operationList()
    {
        $input = Request()->param();

        $list = Db::name('operation_log')->order('id desc')->paginate();
        $this->assign('list', $list);

        $this->assign('title', '操作日志');
        return $this->view->fetch();
    }
}
